<i18n locale="en" lang="yaml">
randomIDString: fsvc-{Random ID}
</i18n>

<i18n locale="zh-CN" lang="yaml">
randomIDString: fsvc-{随机 ID}

Add File Service  : 添加文件服务
Setup File Service: 配置文件服务

Customize ID: 定制 ID
Root        : 根目录
Note        : 备注

URL Preview: URL预览
ID is used in the access URL: 此 ID 用于生成访问时的 URL

'ID must starts with "{prefix}"': 'ID 必须以"{prefix}"开头'
'Only numbers, alphabets, dot(.), underscore(_) and hyphen(-) are allowed': 只能输入数字、英文、点（.）、下划线（_）以及连字符（-）
Please select root: 请选择根目录

File Service created: 文件服务已创建
File Service saved  : 文件服务已保存
File Service deleted: 文件服务已删除

Are you sure you want to delete the File Service?: 是否确认删除此文件服务？
</i18n>

<!-- Generated by OpenCC START -->
<i18n locale="zh-HK" lang="yaml">
Add File Service: 添加文件服務
Are you sure you want to delete the File Service?: 是否確認刪除此文件服務？
Customize ID: 定製 ID
File Service created: 文件服務已創建
File Service deleted: 文件服務已刪除
File Service saved: 文件服務已保存
ID is used in the access URL: 此 ID 用於生成訪問時的 URL
ID must starts with "{prefix}": ID 必須以"{prefix}"開頭
Note: 備註
Only numbers, alphabets, dot(.), underscore(_) and hyphen(-) are allowed: 只能輸入數字、英文、點（.）、下劃線（_）以及連字符（-）
Please select root: 請選擇根目錄
Root: 根目錄
Setup File Service: 配置文件服務
URL Preview: URL預覽
randomIDString: fsvc-{隨機 ID}
</i18n>
<i18n locale="zh-TW" lang="yaml">
Add File Service: 新增檔案服務
Are you sure you want to delete the File Service?: 是否確認刪除此檔案服務？
Customize ID: 定製 ID
File Service created: 檔案服務已建立
File Service deleted: 檔案服務已刪除
File Service saved: 檔案服務已儲存
ID is used in the access URL: 此 ID 用於生成訪問時的 URL
ID must starts with "{prefix}": ID 必須以"{prefix}"開頭
Note: 備註
Only numbers, alphabets, dot(.), underscore(_) and hyphen(-) are allowed: 只能輸入數字、英文、點（.）、下劃線（_）以及連字元（-）
Please select root: 請選擇根目錄
Root: 根目錄
Setup File Service: 配置檔案服務
URL Preview: URL預覽
randomIDString: fsvc-{隨機 ID}
</i18n>
<!-- Generated by OpenCC END -->

<template>
  <el-dialog
    id="ScriptSetSetup"
    :visible.sync="show"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    width="750px">

    <template slot="title">
      {{ pageTitle }} <code class="text-main">{{ data.root }}</code>
    </template>

    <el-container direction="vertical">
      <el-main>
        <div class="setup-form">
          <el-form ref="form" label-width="135px" :model="form" :rules="formRules">
            <el-form-item :label="$t('Customize ID')" prop="useCustomId" v-if="pageMode === 'add'">
              <el-switch v-model="useCustomId"></el-switch>
              <span class="text-main float-right">
                {{ $t('URL Preview') }}{{ $t(':') }}
                <code>{{ `/api/v1/fs/${useCustomId ? form.id : $t('randomIDString')}` }}</code>
              </span>
            </el-form-item>

            <el-form-item label="ID" prop="id" v-show="useCustomId" v-if="pageMode === 'add'">
              <el-input
                maxlength="60"
                v-model="form.id">
              </el-input>
              <InfoBlock :title="$t('ID is used in the access URL')" />
            </el-form-item>

            <el-form-item :label="$t('Root')" prop="root">
              <el-cascader ref="rootCascader"
                placeholder="--"
                separator=""
                v-model="form.root"
                :props="rootCascaderProps"></el-cascader>
            </el-form-item>

            <el-form-item :label="$t('Note')">
              <el-input :placeholder="$t('Optional')"
                type="textarea"
                resize="none"
                :autosize="{minRows: 2}"
                maxlength="5000"
                v-model="form.note"></el-input>
            </el-form-item>

            <el-form-item class="setup-footer">
              <el-link type="danger" class="float-left" v-if="pageMode === 'setup'" @click="deleteData">{{ $t('Delete') }}</el-link>
              <el-button type="primary" v-prevent-re-click @click="submitData">{{ $t('Save') }}</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-main>
    </el-container>
  </el-dialog>
</template>

<script>
export default {
  name: 'FileServiceSetup',
  components: {
  },
  watch: {
    show(val) {
      if (val && this.$refs.form) {
        this.$refs.form.clearValidate();
      }

      if (!val) {
        this.$root.$emit('reload.fileServiceList');
      }
    },
    useCustomId(val) {
      if (val) {
        this.form.id = `${this.ID_PREFIX}my-file-service`;
      } else {
        this.form.id = null;
      }
    },
  },
  methods: {
    async loadData(id) {
      if (!id) {
        this.pageMode = 'add';
        this.T.jsonClear(this.form);
        this.data = {};

      } else {
        this.pageMode = 'setup';
        this.data.id = id;

        let apiRes = await this.T.callAPI_getOne('/api/v1/file-services/do/list', this.data.id);
        if (!apiRes || !apiRes.ok) return;

        this.data = apiRes.data;

        let nextForm = {};
        Object.keys(this.form).forEach(f => nextForm[f] = this.data[f]);
        this.form = nextForm;
      }

      this.show = true;

      setImmediate(() => {
        this.$refs.rootCascader.presentText = this.data.root;
      });
    },
    async submitData() {
      try {
        await this.$refs.form.validate();
      } catch(err) {
        return console.error(err);
      }

      switch(this.pageMode) {
        case 'add':
          return await this.addData();
        case 'setup':
          return await this.modifyData();
      }
    },
    async addData() {
      let apiRes = await this.T.callAPI('post', '/api/v1/file-services/do/add', {
        body    : { data: this.T.jsonCopy(this.form) },
        feedback: { okMessage: this.$t('File Service created') },
      });
      if (!apiRes || !apiRes.ok) return;

      this.$store.commit('updateHighlightedTableDataId', apiRes.data.id);
      this.show = false;
    },
    async modifyData() {
      let _formData = this.T.jsonCopy(this.form);
      delete _formData.id;

      let apiRes = await this.T.callAPI('post', '/api/v1/file-services/:id/do/modify', {
        params  : { id: this.data.id },
        body    : { data: _formData },
        feedback: { okMessage: this.$t('File Service saved') },
      });
      if (!apiRes || !apiRes.ok) return;

      this.$store.commit('updateHighlightedTableDataId', apiRes.data.id);
      this.show = false;
    },
    async deleteData() {
      if (!await this.T.confirm(this.$t('Are you sure you want to delete the File Service?'))) return;

      let apiRes = await this.T.callAPI('/api/v1/file-services/:id/do/delete', {
        params  : { id: this.data.id },
        feedback: { okMessage: this.$t('File Service deleted') },
      });
      if (!apiRes || !apiRes.ok) return;

      this.show = false;
    },
  },
  computed: {
    ID_PREFIX() {
      return 'fsvc-';
    },
    pageTitle() {
      const _map = {
        setup: this.$t('Setup File Service'),
        add  : this.$t('Add File Service'),
      };
      return _map[this.pageMode];
    },
  },
  props: {
  },
  data() {
    return {
      show    : false,
      pageMode: null,

      data: {},

      useCustomId: false,

      form: {
        id  : null,
        root: null,
        note: null,
      },
      formRules: {
        id: [
          {
            trigger: 'change',
            validator: (rule, value, callback) => {
              if (this.T.notNothing(value)) {
                if ((value.indexOf(this.ID_PREFIX) !== 0 || value === this.ID_PREFIX)) {
                  return callback(new Error(this.$t('ID must starts with "{prefix}"', { prefix: this.ID_PREFIX })));
                }
                if (!value.match(/^[0-9a-zA-Z\.\-\_]+$/g)) {
                  return callback(new Error(this.$t('Only numbers, alphabets, dot(.), underscore(_) and hyphen(-) are allowed')));
                }
              }
              return callback();
            },
          }
        ],
        root: [
          {
            trigger : 'blur',
            message : this.$t('Please select root'),
            required: true,
          },
        ],
      },

      rootCascaderProps: {
        expandTrigger: 'hover',
        emitPath     : false,
        multiple     : false,
        checkStrictly: true,
        lazy         : true,
        lazyLoad: async (node, resolve) => {
          let apiRes = await this.T.callAPI_get('/api/v1/resources/do/list', {
            query: { folder: node.value, type: 'folder' },
          });
          if (!apiRes || !apiRes.ok) return;

          let baseFolder = node.value || '';
          if (baseFolder && !this.T.endsWith(baseFolder, '/')) {
            baseFolder += '/';
          }

          let nodes = apiRes.data.map(d => ({
            label: `${d.name}/`,
            value: `${baseFolder}${d.name}/`,
          }));

          resolve(nodes);
        }
      },
    }
  },
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
